package com.hkrda523bpwp.hkr_da523b_projekt_pwp;

import android.app.ActionBar;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.CheckBox;

public class LocationHandler {
	
	public LocationManager locationManager;
	public LocationProvider lProvider;
	private ViewPagerNoSwipe mViewPager;
	private ActionBar.Tab abt;
	private CheckBox ch;
	
	private double latitude;
	private double longitude;
	
	private boolean isSet = false;
	
	public void setABT(ActionBar.Tab abt){
		this.abt = abt;
	}
	
	public boolean isSet(){
		return isSet;
	}
	
	public double getLatitude(){
		return this.latitude;
	}
	
	public double getLongitude(){
		return this.longitude;
	}
	
	public LocationHandler (Context context, ViewPagerNoSwipe mViewPager){
		locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		lProvider = locationManager.getProvider(LocationManager.NETWORK_PROVIDER);
		this.mViewPager = mViewPager;
	}	
	
	private void setKE(){
		if (abt.getPosition() == 2){
			if (isSet == false){
				ch.setChecked(false);
				ch.setEnabled(false);
				ch.setText("Väntar på position...");
			} else {
				ch.setEnabled(true);
				ch.setText("Skicka position");
			}
		}
	}

	private final LocationListener listener = new LocationListener(){

		@Override
		public void onLocationChanged(Location location) {
			longitude = location.getLongitude();
			latitude = location.getLatitude();
			isSet = true;
			locationManager.removeUpdates(listener);
			setKE();
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
		
	};
	
	public void start(){
		isSet = false;
		locationManager.requestLocationUpdates(lProvider.getName(), 100, 0, listener);
		if (abt.getPosition() == 2){
			ch = (CheckBox) mViewPager.getRootView().findViewById(R.id.booking_checkBox_KE);
			setKE();
		}
	}
	
	public void stop(){
		locationManager.removeUpdates(listener);
		isSet = false;
	}
}
